/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import DefaultValueOperator from '../../../scripts/defaultValueOperator.js';

const SINGLE_SELECT = 0; // 单选模式
const MULTI_SELECT = 1; // 多选模式

export const ITEM_HEIGHT_1 = 48;
export const ITEM_HEIGHT_2 = 68;
export const LIST_MAX_HEIGHT = 350;
export default {
  props: ['config', 'data'],
  data: {
    mode: SINGLE_SELECT,
    items: [],
    defaultIndex: [],
    inactiveIcon: undefined,
    activeIcon: undefined,
    listHeight: 0,
  },
  onInit() {
    this.$watch('config', 'configUpdate')
    this.$watch('data', 'dataUpdate')
    this.initConfig()
    this.initData()
  },
  configUpdate(newV, oldV) {
    this.config = newV
    this.initConfig()
  },
  dataUpdate(newV, oldV) {
    this.initData()
  },
  initConfig() {
    if (this.config == undefined) {
      return
    }
    this.mode = DefaultValueOperator.numberValue(this.config.mode, this.mode)
    this.items = this.config.items
    this.inactiveIcon = this.config.inactiveIcon
    this.activeIcon = this.config.activeIcon
    this.itemCanClick = DefaultValueOperator.booleanValue(this.config.itemCanClick, this.itemCanClick)
    this.computedListHeight(this.items)
  },
  initData() {
    if (this.data == undefined) {
      return
    }
    this.defaultIndex = DefaultValueOperator.arrayValue(this.data.defaultIndex, this.defaultIndex)
  },
  computedListHeight(items) {
    this.listHeight = 0
    items.forEach((item) => {
      if (item.subTitle == undefined || item.subTitle == '') {
        this.listHeight = this.listHeight + ITEM_HEIGHT_1
      } else {
        this.listHeight = this.listHeight + ITEM_HEIGHT_2
      }
    })
    if (this.listHeight > this.listMaxHeight) {
      this.listHeight = this.listMaxHeight
    }
  },
  onSingleSelect(params) {
    this.defaultIndex = params.detail.index
    this.$emit('onChangeIndex', {
      index: this.defaultIndex,
    })
  },
  onMultiSelect(params) {
    let index = this.defaultIndex.indexOf(params.detail.index);
    if (index >= 0) {
      this.defaultIndex.splice(index, 1)
    } else {
      this.defaultIndex.push(params.detail.index)
    }
    this.$emit('onChangeIndex', {
      index: this.defaultIndex,
    })
  }
}